<?php
namespace Api;
use Kuyuan\WqCore\api\Api;
use Kuyuan\WqCore\util\DB;
use Kuyuan\WqCore\util\Util;
use Yansongda\Pay\Exceptions\Exception;
use Yansongda\Pay\Pay;

/**
 * 红包信息
 * Class SendRed
 * @package Api
 */
class Red extends Api
{
    private $Red = null;

    public function __construct()
    {
        parent::__construct();
        $this->Red = $this->newController("Red");
    }

    /**
     * 获取红包列表
     */
    public function getUserList()
    {
        Util::appointGet();
        $_enter_red_id = 0;
        if(isset($this->_gpc["enter_red_id"])) $_enter_red_id = $this->_gpc["enter_red_id"];
        $_list = $this->Red->getUserList($this->_gpc["limit"],$_enter_red_id);
        if (count($_list) > 0) {
            $_result = array("code" => 0, "data" => $_list);
        } else {
            $_result = array("code" => 101);
        }
        Util::returns($_result);
    }

    /**
     * 一个红包数据
     */
    public function find()
    {
        Util::appointGet();
        $_data = $this->Red->getHomeOne($this->_gpc["red_id"]);
        if (!$_data || $_data["status"] < 2 || $_data["status"] >= 6) {
            $_result = array("code" => 100);
        } else {
            $_data["numbered"] = $this->Red->numbered($this->_gpc["red_id"]);
            $_result = array("code" => 0, "data" => $_data);
        }
        Util::returns($_result);
    }

    /**
     * 修改时获取一个红包的数据
     */
    public function get()
    {
        Util::appointGet();
        $_data = $this->Red->get($this->_gpc["red_id"]);
        if (!$_data || $_data["status"] < 2 || $_data["status"] >= 6) {
            $_result = array("code" => 100);
        } else {
            $_result = array("code" => 0, "data" => $_data);
        }
        Util::returns($_result);
    }

    /**
     * 获取首页红包列表
     */
    public function getHomeList()
    {
        Util::appointPost();
        $_enter_red = isset($this->_gpc["enter_red"]) ? $this->_gpc["enter_red"] : 0;
        $_area = "";
        if(is_array($this->_gpc["area"]) && count($this->_gpc["area"]) > 0) {
            $_area = implode("/",$this->_gpc["area"]);
        }
        $_data = $this->Red->getHomeList($this->_gpc["limit"],$_area,$_enter_red);
        if (count($_data) > 0) {
            $_result = array("code" => 0, "data" => $_data);
        } else {
            $_result = array("code" => 101);
        }
        Util::returns($_result);
    }

    /**
     * 获取首页红包列表可开红包总数
     */
    public function getHomeListTotal()
    {
        Util::appointPost();
        if($_total = $this->Red->getHomeListTotal()) {
            $_result = array("code" => 0,"data"=>$_total);
        } else {
            $_result = array("code" => 106);
        }
        Util::returns($_result);
    }

    /**
     * 验证发红包权限
     */
    public function checkAccess()
    {
        Util::appointGet();
        $Setting = $this->newController("Setting");
        $_setting = $Setting->find();
        $RedAccess = $this->newController("RedAccess");
        $_user_access = $RedAccess->value("status");
        if(!$_setting["open_send"] && $_user_access != 2) {
            $_result = array("code"=>0,"data"=>0);
        } else {
            $_result = array("code"=>0,"data"=>1);
        }
        Util::returns($_result);
    }

    /**
     * 获取后台管理红包列表
     */
    public function getManageList()
    {
        Util::appointGet();
        $_list = $this->Red->getManageList($this->_gpc["limit"]);
        if($_list) {
            $_result = array("code"=>0,"data"=>$_list);
        } else {
            $_result = array("code"=>101);
        }
        Util::returns($_result);
    }

    /**
     * 后台管理列表红包总数
     */
    public function getManageTotal()
    {
        Util::appointGet();
        Util::returns(array("code"=>0,"data"=>$this->Red->getManageTotal()));
    }

    /**
     * 删除红包
     */
    public function del()
    {
        Util::appointPost();
        DB::begin();
        try{
            $_red = $this->Red->take($this->_gpc["red_id"]);
            if(!$_red || ($_red["status"] != 2 && $_red["status"] != 4)) {
                throw new \PDOException("非法操作",100);
            }
            if($_red["numbered"] < $_red["number"]) {
                // 红包未发完，退款给发包用户
                $_pay_type = $this->Red->value($this->_gpc["red_id"],"pay_type");
                // 获取红包剩余金额
                $_surplus_money = $this->Red->getRedBalance($this->_gpc["red_id"]);
                if($_pay_type == 1) {
                    // 余额，返回给用户余额
                    $Member = $this->newController("Member");
                    $Member->financeHandle($_surplus_money,true,$_red["uid"]);
                } else {
                    // 微信支付退款
                    $_pay_config = \Kuyuan\WqCore\wx\Pay::config(false);
                    \Kuyuan\WqCore\wx\Pay::getCertKey($_pay_config["cert_client"],$_pay_config["cert_key"]);
                    // 支付订单id
                    $MchOrder = $this->newController("MchOrder");
                    $_mch_order = $MchOrder->find($this->_gpc["red_id"]);
                    // 创建退款订单
                    $MchRefund = $this->newController("MchRefund");
                    $_refund_order_id = $MchRefund->create(
                        $_mch_order["order_id"],
                        $_surplus_money,
                        $_red["uid"]
                    );
                    try{
                        $Setting = $this->newController("Setting");
                        $_setting = $Setting->find();
                        $_refund_result = Pay::wechat($_pay_config)->refund(array(
                            'out_trade_no' => $_mch_order["order_id"],
                            'out_refund_no' => $_refund_order_id,
                            'total_fee' => $_mch_order["money"] * 100,
                            'refund_fee' => $_surplus_money * 100,
                            'refund_desc' => $_setting["app_name"]."-红包删除，剩余未发红包余额退款"
                        ));
                        \Kuyuan\WqCore\wx\Pay::clearCertKey($_pay_config["cert_client"],$_pay_config["cert_key"]);
                        $MchRefund->edit($_refund_order_id,array("status"=>1));
                    } catch (Exception $e) {
                        \Kuyuan\WqCore\wx\Pay::clearCertKey($_pay_config["cert_client"],$_pay_config["cert_key"]);
                        $_message = explode(':',$e->getMessage());
                        throw new \PDOException(end($_message),700);
                    }
                }
            }
            if(!$this->Red->edit($this->_gpc["red_id"],array("status"=>9))) {
                throw new \PDOException("删除失败",102);
            }
            DB::commit();
            Util::returns(array("code"=>0));
        }catch (\PDOException $e) {
            DB::back();
            Util::returns(array("code"=>$e->getCode(),"err_msg"=>$e->getMessage()));
        }
    }

    /**
     * 暂停停止发红包
     */
    public function stop()
    {
        Util::appointPost();
        try {
            if(!$this->Red->edit($this->_gpc["red_id"],array("status"=>4))) {
                throw new \Exception("",103);
            }
            Util::returns(array("code"=>0));
        }catch (\Exception $e) {
            Util::returns(array("code"=>$e->getCode()));
        }
    }

    /**
     * 开始发红包
     */
    public function start()
    {
        Util::appointPost();
        try {
            if(!$this->Red->edit($this->_gpc["red_id"],array("status"=>2))) {
                throw new \Exception("",103);
            }
            Util::returns(array("code"=>0));
        }catch (\Exception $e) {
            Util::returns(array("code"=>$e->getCode()));
        }
    }

}